#!/bin/bash

set -eux # -x for verbose logging to juju debug-log

juju-log "III Getting any config parameters."

szAcceptDataViaUdp=`config-get AcceptUdpConnections`
szAcceptDataViaUdpDefault="True"

if [ -z "$szAcceptDataViaUdp" ]
then
  szAcceptDataViaUdp="True"
  juju-log "DDD Not set: AcceptUdpConnections, default to: $szAcceptDataViaUdp"
else
  # TODO make sure that it is only true or false, anything and it must got back to the default value.
  juju-log "DDD AcceptUdpConnections: $szAcceptDataViaUdp"
fi

##############################
# INSTALL SYSTEM DEPENDENCIES
#############################
juju-log "III Updating the package list."
apt-get update

juju-log "III Installing apache2,sqlite3, pythondev rabbitmq-server via apt-get"
apt-get -y install apache2 libapache2-mod-wsgi libapache2-mod-python memcached python-dev python-cairo-dev python-django python-ldap python-memcache python-pysqlite2 python-pip sqlite3 erlang-os-mon erlang-snmp rabbitmq-server python-django-tagging
#libapache2-mod-python memcached python-dev python-cairo-dev /
#python-django python-ldap python-memcache python-pysqlite2 /
#python-pip sqlite3 erlang-os-mon erlang-snmp rabbitmq-server
  
 
#################
# INSTALL WHISPER
#################
 
juju-log "III Install Whisper."
wget http://launchpad.net/graphite/0.9/0.9.9/+download/whisper-0.9.9.tar.gz
pip install whisper-0.9.9.tar.gz
rm whisper-0.9.9.tar.gz
 
################################################
# INSTALL AND CONFIGURE CARBON (data aggregator)
################################################
 
juju-log "III Install and configure carbon."
pushd /tmp
wget http://launchpad.net/graphite/0.9/0.9.9/+download/carbon-0.9.9.tar.gz
tar -zxf carbon-0.9.9.tar.gz
cd carbon-0.9.9
python setup.py install
cd /opt/graphite/conf/
cp carbon.conf.example carbon.conf
cp storage-schemas.conf.example storage-schemas.conf
popd
 
###########################
# INSTALL GRAPHITE (webapp)
###########################
 
juju-log "III install graphite."
cd /tmp
wget http://launchpad.net/graphite/0.9/0.9.9/+download/graphite-web-0.9.9.tar.gz
tar -zxvf graphite-web-0.9.9.tar.gz
mv graphite-web-0.9.9 graphite
cd graphite
python check-dependencies.py
python setup.py install
 
##################
# CONFIGURE APACHE
##################
 
juju-log "III Configure apache."
cd /tmp/graphite/examples
cp example-graphite-vhost.conf /etc/apache2/sites-available/default
cp /opt/graphite/conf/graphite.wsgi.example /opt/graphite/conf/graphite.wsgi
mkdir /etc/httpd
mkdir /etc/httpd/wsgi
/etc/init.d/apache2 reload
 
#########################
# CREATE INITIAL DATABASE
#########################
 
juju-log "Create initial database."
cd /opt/graphite/webapp/graphite/
python manage.py syncdb  --noinput
chown -R www-data:www-data /opt/graphite/storage/
/etc/init.d/apache2 restart
cp local_settings.py.example local_settings.py
